﻿using DrawTools.Serialize;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DrawTools.Tools
{
    /// <summary>
    /// 闭合线条
    /// </summary>
    [SerializerType(typeof(DrawClosedLineSerializer))]
    public sealed class ClosedLineDrawTool : DrawGeometryBase
    {
        #region 字段

        private List<Point> points = new List<Point>();

        #endregion 字段
        public ClosedLineDrawTool(DrawingCanvas drawingCanvas) : base(drawingCanvas)
        {
            DrawingToolType = DrawToolType.ClosedLine;
        }

        #region 鼠标键盘事件

        public override bool OnTouchDown(int touchId, Point point)
        {
            TouchId = touchId;

            drawingCanvas.AddWorkingDrawTool(this); drawingCanvas.AddVisual(this); drawingCanvas.handleCursor = true;

            CanTouchDown = false;

            points.Add(point);

            geometry = new PathGeometry();

            var figure = new PathFigure { StartPoint = point };
            pathGeometry.Figures.Add(figure);

            CanTouchMove = true; CanTouchUp = true;

            if (TouchId != 0 || !drawingCanvas.CaptureMouse()) CanTouchLeave = true;

            return true;
        }

        public override bool OnTouchMove(Point point)
        {
            if ((point - points.Last()).Length < Pen.Thickness) return true;

            points.Add(point);

            var figure = pathGeometry.Figures[0]; var line = new LineSegment(point, IsStroked)
            {
                IsSmoothJoin
            = true
            }; figure.Segments.Add(line);

            var dc = RenderOpen(); dc.DrawGeometry(null, Pen, geometry); dc.Close();

            return true;
        }

        public override bool OnTouchUp(Point point)
        {
            if (points.Count < 2) drawingCanvas.DeleteVisual(this);
            else
            {
                point = points.Last(); var first = points[0];

                var figure = pathGeometry.Figures[0]; var line = new LineSegment(first, IsStroked)
                {
                    IsSmoothJoin = true
                };
                figure.Segments.Add(line);
                geometry = geometry.GetWidenedPathGeometry(Pen);
                Draw();
            }

            drawingCanvas.DeleteWorkingDrawTool(this);

            IsFinish = true;

            CanTouchMove = false; CanTouchUp = false; CanTouchLeave = false;

            if (TouchId == 0 && drawingCanvas.IsMouseCaptured) drawingCanvas.ReleaseMouseCapture();

            drawingCanvas.handleCursor = false;

            return true;
        }

        #endregion 鼠标键盘事件

    }
}